package com.kang.aop.loginAop;

import com.alibaba.fastjson.JSON;
import com.kang.entity.SysLoginLog;
import com.kang.entity.SysUser;
import com.kang.service.SysLoginLogService;
import com.kang.util.HttpContextUtils;
import com.kang.util.IPUtils;
import com.kang.util.ToStringUtils;
import com.kang.util.WebResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Arrays;

/**
 * 登录日志，切面处理类
 *
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {
	@Autowired
	private SysLoginLogService sysLogService;
	
	//定义切点 切点表达式指向SysLog注解，我们再业务方法上可以加上SysLog注解，然后所标注
	//的方法都能进行日志记录
	@Pointcut("@annotation(com.kang.aop.loginAop.SysLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public WebResponse around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		//执行方法
		WebResponse result = (WebResponse) point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;
		//保存日志
		saveSysLog(point, time,result);
		return result;
	}

	private void saveSysLog(ProceedingJoinPoint joinPoint, long time,WebResponse result) {
		SysLoginLog sysLog = new SysLoginLog();

		//请求的参数
		Object[] args = joinPoint.getArgs();
		SysUser sysUser = new SysUser();
		try{
			String params = Arrays.toString(args);
			String jsonString = ToStringUtils.toJSONString(params.substring(1,params.length() - 2));
			sysUser = JSON.parseObject(jsonString, SysUser.class);
//			sysLog.setParams(params);
		}catch (Exception e){
			log.info("loginAop切面获取请求参数失败",e);
		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		String ipAddr = IPUtils.getIpAddr(request);
		assert sysUser != null;
		sysLog.setUsername(sysUser.getUsername());
		sysLog.setIpaddr(ipAddr);
		if ("0000".equals(result.getCode())) {
			sysLog.setStatus(0);
		} else {
			sysLog.setStatus(1);
		}
		sysLog.setAccessTime(time);
		sysLog.setMsg(result.getMsg());
		//保存系统日志
		sysLogService.save(sysLog);
	}

	public static void main(String[] args) throws ParseException {
		String s = "SysUser(username=admin, password=111111, name=null, phone=null, headUrl=null, description=null, status=null, roleList=null)";
		String jsonString = ToStringUtils.toJSONString(s);
		SysUser sysUser = JSON.parseObject(jsonString, SysUser.class);
		System.out.println(sysUser.getUsername());
	}
}
